#include "common.h"

struct Account1
{
	int num;
	char name[100];
	char pwd[20];
	double balance;	
};

int substrfile(const char * filename)
{
	char buf[10] = {};
	char *p = filename;
	int pos = 0;
	for( ; *p != '\0' ; ++p)
	{
		if(*p == '.')
		{			
			return pos;
		}
		++pos;
	}
}


int Findfile(const char * path)
{
	DIR * dir = opendir(path);
		if(dir == NULL) perror("opendir") , exit(-1);
	struct dirent * dirent = readdir(dir);	
	int temp = 0;
	char filename[10] = {};
	while((dirent = readdir(dir)) != NULL)
	{		
		if(dirent->d_type == 8)
		{
			strncpy(filename,dirent->d_name,substrfile(dirent->d_name));
			if(atoi(filename) > temp)
			{
				temp = atoi(filename);
			}
		}		
	}
	return temp;
}

int writeinto()
{
	int fd = open("a.bat",O_CREAT | O_RDWR , 0666);
	struct Account1 acc;
	acc.num = 100;
	strcpy(acc.name , "Chris");
	strcpy(acc.pwd , "bbb");
	acc.balance = 2000.3;
	write(fd , &acc , sizeof(acc));
	close(fd);
}

int readfrom()
{
	int fd = open("a.bat",O_RDWR , 0666);
	struct Account1 acc;
	read(fd , &acc , sizeof(acc));
	printf("acc.balance : %f\n",acc.balance);
	close(fd);	
}

int update()
{
	int fd = open("a.bat",O_RDWR , 0666);
	struct Account1 acc;
	read(fd , &acc , sizeof(acc));
	printf("acc.balance : %f\n",acc.balance);
	acc.balance += 1000;
	lseek(fd , 0 , SEEK_SET);
	write(fd , &acc , sizeof(acc));
	close(fd);
}

void saveMoney()
{
	//1.input the name of account closed
	struct Msg m1;
	m1.mtype = M_SAVE;
	double saveMoney = 0;
	printf("input account of id you want to save : ");
	scanf("%d",&m1.acc.num);
	printf("input the amount of money want to save : ");
	scanf("%lf",&saveMoney);
	m1.acc.balance = saveMoney;
	printf("saveMoney : %f\n",saveMoney);
}

void main()
{
	//printf("%d\n",Findfile("./user"));
	/*writeinto();
	update();
	readfrom();*/
	saveMoney();
}
